//
//  HGMVsecViewController.m
//  悦享
//
//  Created by dllo on 16/3/31.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "HGMVsecViewController.h"
#import "SongMVModel.h"
#import "SongModel.h"
#import "HGAVPlayerManager.h"
#import <AFNetworking.h>
#import <MediaPlayer/MediaPlayer.h>
#import "HGMvTableViewCell.h"
#import <MBProgressHUD.h>

@interface HGMVsecViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) NSMutableArray *dataArr;/**<  数据源属猪 */


@property (nonatomic, retain) UIView *playView;/**<  播放器地波view */

@property (nonatomic, retain) UIButton *backButton;/**<  返回button */

@property (nonatomic, retain) UIView *backAlphaView;/**<  按钮下面的透明view */
@property (nonatomic, retain) UIButton *playButton;/**<  播放按钮 */

@property (nonatomic, assign) BOOL isPlay;/**<  是否在播放 */
@property (nonatomic, assign) BOOL isTap;/**<  是否点击屏幕 */

@property (nonatomic, retain) UISlider *progressSlider;/**<  滑动条 */

@property (nonatomic, retain) UIButton *quanPingButton;/**<  全屏按钮 */

@property (nonatomic, retain) UILabel *timeLabel;/**<  显示时间的label */
@property (nonatomic, assign) CGFloat totaDuration;/**< 记录全部时间 */

@property (nonatomic, retain) UITableView *tableView;/**<  下边的tableVeiw */

@property (nonatomic, retain) NSString *filePath;/**<  afn下载路径 */

@property (nonatomic, retain) UIProgressView *progressV;/**<  下载条 */

@property (nonatomic, retain) NSURLSessionDownloadTask *downLoadTask;


@property (nonatomic, assign) BOOL isHengPing;/**<  标记横屏 */


@end

@implementation HGMVsecViewController


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.07 green:0.2 blue:0.24 alpha:1];
    _isPlay = YES;
    _isPlay = NO;
    
    _isHengPing = YES;
    
    [self handleData];
    
   
    
    
  
    
    
    
}
/**
 *  创建下载读取条
 */
- (void)createProgressV{
    self.progressV = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressV.frame = CGRectMake(65,  14, SREEN_WIDTH - 130, 10);
    
    _progressV.backgroundColor = [UIColor clearColor];
    _progressV.progressTintColor = [UIColor lightGrayColor];
    _progressV.trackTintColor = [UIColor clearColor];
    [_backAlphaView addSubview:_progressV];
}

//创建tableView
- (void)createTableView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 200, SREEN_WIDTH, SREEN_HEIGHT - 200) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [_tableView registerClass:[HGMvTableViewCell class] forCellReuseIdentifier:@"HGMvTableViewCell"];
    
}
#pragma mark- tableView代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return 0;
    }
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HGMvTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGMvTableViewCell"];
    SongModel *model = _dataArr[indexPath.row];
    
    cell.model = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"推荐MV";
    }else{
        return @"";
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        SongModel *model = _dataArr[indexPath.row];
        
        SongMVModel *modelMV = [model.mvListArr lastObject];
        
        self.videoId = [modelMV.videoId stringValue];
        
        [self handleData];
        
        self.playView = [[HGAVPlayerManager shareHGVideoPlayerManager] createAvPlayerWithUrl:modelMV.url];
        
        
    }
    
    
}

/**<  创建返回按钮 */
- (void)createFunHuiButton{
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _backButton.frame = CGRectMake(20, 20, 20, 20);
    [_backButton setImage:[UIImage imageNamed:@"iconfont-zuojiantou"] forState:UIControlStateNormal];
    
    [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_backButton];
}
/**
 *  返回按钮
 *
 *  @param button
 */
- (void)backButtonAction:(UIButton *)button{
    //暂停
    [[HGAVPlayerManager shareHGVideoPlayerManager] pause];
    [_backAlphaView removeFromSuperview];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

/**
 *  进度监听方法
 */
- (void)addNotificationCenter{
    // 添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
//适配全屏
- (void)setPlayFrame {
    
    [HGAVPlayerManager shareHGVideoPlayerManager].playerLayer.frame = CGRectMake(0, 0, SREEN_WIDTH, SREEN_HEIGHT);
    NSLog(@"%f", SREEN_HEIGHT);
    _backAlphaView.frame = CGRectMake(0, SREEN_HEIGHT - 40, SREEN_WIDTH, 40);
    
    _progressV.frame = CGRectMake(65, 8, SREEN_WIDTH - 130, 10);
    _progressSlider.frame = CGRectMake(65,  8, SREEN_WIDTH - 130, 10);
    _progressSlider.center = _progressV.center;
    _quanPingButton.frame = CGRectMake(SREEN_WIDTH - 50, 6, 30, 30);
    _playView.frame = CGRectMake(0, 0, SREEN_WIDTH, SREEN_HEIGHT);
}

//竖屏
- (void)setPlayFrame1{
    
    [HGAVPlayerManager shareHGVideoPlayerManager].playerLayer.frame = CGRectMake(0, 0, SREEN_WIDTH, 200);
    _playView.frame = CGRectMake(0, 0, SREEN_WIDTH, SREEN_HEIGHT);
    
    self.playView.frame = CGRectMake(0, 0, SREEN_WIDTH, 200);
    _progressV.frame = CGRectMake(65, 8, SREEN_WIDTH - 130, 10);
    _progressSlider.frame = CGRectMake(65,  8, SREEN_WIDTH - 130, 10);
    _progressSlider.center = _progressV.center;
    _quanPingButton.frame = CGRectMake(SREEN_WIDTH - 50, 6, 30, 30);
    NSLog(@"%f", SREEN_HEIGHT);
}
/**<  当监听屏幕发生变化时执行 */
- (void)statusBarOrientationChange:(NSNotification *)notification{
    
    
    
    // 获取到当前屏幕旋转的方向
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"向左横屏");
        [self setPlayFrame];
        _tableView.hidden = YES;
        _isHengPing = NO;
        _backButton.hidden = YES;
    }
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"向右横屏");
        [self setPlayFrame];
        _tableView.hidden = YES;
        _isHengPing = NO;
        _backButton.hidden = YES;
    }
    if (orientation == UIInterfaceOrientationPortrait) {
        NSLog(@"竖屏");
        [self setPlayFrame1];
        _tableView.hidden = NO;
        _isHengPing = YES;
        _backButton.hidden = NO;
    }
    
}


/**<  创建播放器 */
- (void)createPlayView{
    
   
    [[HGAVPlayerManager shareHGVideoPlayerManager] play];
    [self addNotificationCenter];
    
    
    
    [self.view addSubview:_playView];
    
    /**<  创建透明view */
    self.backAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0,_playView.frame.size.height, SREEN_WIDTH, 40)];
    _backAlphaView.backgroundColor = [UIColor blackColor];
    _backAlphaView.alpha = 0.7;
    _backAlphaView.userInteractionEnabled = YES;
    [_playView addSubview:_backAlphaView];
    
    /**<  创建播放button */
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(5, 5, 30, 30);
    [_playButton setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backAlphaView addSubview:_playButton];
    
    
    /**<  创建下载滚动条 */
    [self createProgressV];
    
    /**<  创建滑动条 */
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(65,  8, SREEN_WIDTH - 130, 10)];
    _progressSlider.center = _progressV.center;
    _progressSlider.value = 0;
    _progressSlider.alpha = 1;
    _progressSlider.backgroundColor = [UIColor clearColor];
    _progressSlider.maximumTrackTintColor = [UIColor clearColor];
    [_progressSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"iconfont-yuan"] forState:UIControlStateNormal];
    [_backAlphaView addSubview:_progressSlider];
    
    /**<  创建全屏button */
    
    self.quanPingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _quanPingButton.frame = CGRectMake(SREEN_WIDTH - 50, 6, 30, 30);
    [_quanPingButton setImage:[UIImage imageNamed:@"iconfont-quanping"] forState:UIControlStateNormal];
    [_quanPingButton addTarget:self action:@selector(quanPingButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backAlphaView addSubview:_quanPingButton];
    
    /**<  创建显示时间的label */
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 20, 100, 20)];
    _timeLabel.text = @"--:--/--:--";
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = [UIFont systemFontOfSize:12];
    [_backAlphaView addSubview:_timeLabel];
    
    /**<  创建手势 */
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_playView addGestureRecognizer:tap];
    
}

/**<  slider的点击方法 */
- (void)sliderAction:(UISlider *)slider{
    
    // 获取到当前进度时间
    CGFloat currentTime = self.totaDuration * slider.value;
    // 转化为CMTime
    CMTime draTime = CMTimeMake(currentTime, 1);
    
    [[HGAVPlayerManager shareHGVideoPlayerManager].avPlayer seekToTime:draTime completionHandler:^(BOOL finished) {
        
        // 到了时间之后 开始播放
        [[HGAVPlayerManager shareHGVideoPlayerManager] play];
    }];
    
    
    
    
}

/**<  全屏按钮方法 点击横屏的方法 */
- (void)quanPingButtonAction:(UIButton *)button{
    
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        _tableView.hidden = NO;
        
        [self setPlayFrame1];
        
        
    } else {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        _tableView.hidden = YES;
        
        [self setPlayFrame];
        
    }
    
}
/**<  手势点击方法 */
- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    
    if (_isHengPing == YES) {
        if (_isTap == NO) {
            [UIView animateWithDuration:0.3 animations:^{
                _backAlphaView.frame = CGRectMake(0, 160, SREEN_WIDTH, 40);
            }];
            
        }else{
            [UIView animateWithDuration:0.3 animations:^{
                _backAlphaView.frame = CGRectMake(0, 200, SREEN_WIDTH, 40);
            }];
        }
        
    }else {
        if (_isTap == NO) {
            [UIView animateWithDuration:0.3 animations:^{
                _backAlphaView.frame = CGRectMake(0, SREEN_HEIGHT - 40, SREEN_WIDTH, 40);
            }];
            
        }else{
            [UIView animateWithDuration:0.3 animations:^{
                _backAlphaView.frame = CGRectMake(0, SREEN_HEIGHT, SREEN_WIDTH, 40);
            }];
        }
        
    }
    
    _isTap = !_isTap;
    
}
#pragma mark 获取字符串时间

- (NSString *)timeToString:(CGFloat)time{
    
    NSInteger minutes = (NSInteger)time / 60; //分钟
    NSInteger seconds = (NSInteger)time % 60; //秒
    //转换为string
    NSString *string = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes,seconds];
    
    return string;
}


//0.1秒block回调的方法
- (void)playTimer:(CGFloat)timer{
    
    self.progressSlider.value = timer / [HGAVPlayerManager shareHGavPlayerManager].sumTime;//给滑竿赋
    
}

- (void)addProgressObserver{
    
    
    
    // CMTime 是专门计算视频的时间格式
    // Core Media
    // 参数1：设置监听的时间间隔
    
    [[HGAVPlayerManager shareHGVideoPlayerManager].avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        // 监听干什么
        // 获取到总的视频时间
        CGFloat duration = CMTimeGetSeconds([HGAVPlayerManager shareHGVideoPlayerManager].playerItem.duration);
        // 获取到当前时间
        CGFloat current = CMTimeGetSeconds([HGAVPlayerManager shareHGVideoPlayerManager].playerItem.currentTime);
        
        // 把总时间转化为字符串显示在lable上
        NSString *durationT = [NSString stringWithFormat:@"%02d:%02d", (int)duration / 60, (int)duration % 60];
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];
        // 拼接字符串显示在lable上
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentT, durationT];
        self.timeLabel.text = timeStr;
        
        // 记录总时间，slider需要使用
        self.totaDuration = duration;
        
        // slider的value
        self.progressSlider.value = current / duration;
        
        
        
        
        
    }];
    
    
}




/**
 *  playButton点击方法
 *
 *  @param button
 */
- (void)playButtonAction:(UIButton *)button{
    if (_isPlay == YES) {
        [_playButton setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
        [[HGAVPlayerManager shareHGVideoPlayerManager] pause];
    }else{
        [_playButton setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [[HGAVPlayerManager shareHGVideoPlayerManager] play];
    }
    _isPlay = !_isPlay;
}

- (void)setVideoId:(NSString *)videoId{
    _videoId = videoId;
}


- (void)handleData{
    
    
    
    
    NSString *str= [NSString stringWithFormat:@"http://api.dongting.com/sim/mv/%@/similarity?app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=9.2.1&active=1&net=2&openudid=72d26f93c0799c325993cf509c2472027f13fa1d&idfa=EA226D01-40F9-413A-A388-906DF3F490F7&utdid=Vu6ZOeT0fJwDAFqPovwyz9bO&alf=201200&bundle_id=com.ttpod.music&latitude=38.88262662462706&longtitude=121.5393874732126", _videoId];
    
    NSLog(@"fffffffffff%@", str);
    
    [APPTools GETWithURL:str par:nil success:^(id responseObject) {
        
        
        NSArray *data = responseObject[@"data"];
        
        self.dataArr = [SongModel baseModelHandleWithArr:data];
        
        
        [_tableView reloadData];
        
        
        SongModel *model = [_dataArr firstObject];
        
        
        
        SongMVModel *modelMV = [model.mvListArr lastObject];
        
        self.playView = [[HGAVPlayerManager shareHGVideoPlayerManager] createAvPlayerWithUrl:modelMV.url];
        
        /**<  创建播放的子视图 */
        [self createPlayView];
        
        /**<  创建tableView */
        [self createTableView];
        /**
         *  添加视频播放条通知
         */
        [self addProgressObserver];
        /**<  创建返回button */
        [self createFunHuiButton];
        
    } filed:^(NSError *error) {
        
    }];
    
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
